﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Business.AllocateManagement.Dto;
using Business.Models;
using Business.PreciseLibraryManagement.Dto;
using Business.ProductCuringManagement.Dto;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.EntityFrameworkCore;
using SixLabors.ImageSharp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using XCZ;
using Yitter.IdGenerator;

namespace Business.PreciseLibraryManagement
{
    public class PreciseLibraryAppService : BusinessWorkFlowAppService,IPreciseLibraryAppService
    {
        private IRepository<PreciseLibrary, Guid> _repository;
        private IRepository<AllocationDesc, Guid> _repository1;

        public PreciseLibraryAppService(IRepository<PreciseLibrary, Guid> repository, IRepository<AllocationDesc, Guid> repository1)
        {
            _repository = repository;
            _repository1 = repository1;
        }

        /// <summary>
        /// 新增或修改精确调拨
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PreciseLibraryDto> CreateOrUpdate(PreciseLibraryDto input)
        {
            PreciseLibrary result = null;
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();
                input.DocumentNumber = YitIdHelper.NextId().ToString();
                PreciseLibrary entity = new PreciseLibrary()
                {
                    DocumentName = input.DocumentName,
                    DocumentNumber = input.DocumentNumber,
                    DateTransfer=input.DateTransfer,
                    WarehouseStaff = input.WarehouseStaff,
                    Associate = input.Associate,
                    Desc = input.Desc,
                    BringRepository = input.BringRepository,
                    RecallProduct=input.RecallProduct,
                };

                foreach (var item in input.createorupdatelibrary)
                {
                    AllocationDesc desc = new AllocationDesc()
                    {
                        CorrelationID = input.Id,
                        Number=item.Number,
                        ProductName=item.ProductName,
                        ProductCode = input.DocumentNumber,
                        SKU = item.SKU,
                        Unit = item.Unit,
                        HandInventory = item.HandInventory,
                        AllocationQuantity = item.AllocationQuantity,
                        OutboundWarehouse = item.OutboundWarehouse,
                        IncomingWarehouse=item.IncomingWarehouse,
                        BatchNumber=item.BatchNumber,
                        CreateTime = item.CreateTime,
                        ValidDate = item.ValidDate,
                        Packing = item.Packing,
                        Desc = item.Desc,
                    };
                    await _repository1.InsertAsync(desc);
                }
                result = await _repository.InsertAsync(ObjectMapper.Map<PreciseLibraryDto, PreciseLibrary>(input));
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
                //检查流程状态
                //await WorkFlow.CheckFormStatus(input.Id.Value, result);
            }

            return ObjectMapper.Map<PreciseLibrary, PreciseLibraryDto>(result);
        }

        /// <summary>
        /// 获取精确调拨列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<PreciseLibraryDto>> GetPreciseLibraryList(PreciseLibraryInputDto input)
        {
            var query = (from b in await _repository.GetQueryableAsync()

                             // on b.TenantId equals d.BorrowId
                         select new PreciseLibraryDto
                         {
                             Id = b.Id,
                             DocumentName = b.DocumentName,
                             DocumentNumber = b.DocumentNumber,
                             DateTransfer = b.DateTransfer,
                             WarehouseStaff = b.WarehouseStaff,
                             Associate = b.Associate,
                             Desc = b.Desc,
                             BringRepository = b.BringRepository,
                             RecallProduct=b.RecallProduct,
                             createorupdatelibrary = (from d in _repository1.GetQueryableAsync().Result
                                                          where b.Id == d.CorrelationID
                                                          select new CreateOrUpdatePreciseLibraryDto
                                                          {
                                                              Number = d.Number,
                                                              ProductName = d.ProductName,
                                                              ProductCode = d.ProductCode,
                                                              SKU = d.SKU,
                                                              Unit = d.Unit,
                                                              HandInventory = d.HandInventory,
                                                              AllocationQuantity=d.AllocationQuantity,
                                                              OutboundWarehouse = d.OutboundWarehouse,
                                                              IncomingWarehouse = d.IncomingWarehouse,
                                                              BatchNumber=d.BatchNumber,
                                                              CreateTime = d.CreateTime,
                                                              ValidDate = d.ValidDate,
                                                              Packing = d.Packing,
                                                              Desc = d.Desc
                                                          }
                             ).ToList()
                         }
                       ).ToList();

            var totalCount = query.Count();
            var items = query.Skip(input.SkipCount - 1).Take(input.MaxResultCount).ToList();

            //var dtos = ObjectMapper.Map<List<BorrowM>, List<BorrowDto>>(items);
            return new PagedResultDto<PreciseLibraryDto>(totalCount, query);
        }

        /// <summary>
        /// 删除精确调拨
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task DeletePreciseLibrary(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }
        }

        /// <summary>
        /// 反填精确调拨
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<PreciseLibraryDto> GetPreciseLibraryForEdit(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<PreciseLibrary, PreciseLibraryDto>(data);
            return dto;
        }

    }
}
